package model;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

/**
 * class RequestsManager - singleton - manage all the updates from the users
 */
public class RequestsManager {
	private static RequestsManager DbManagerSingelton= new RequestsManager();
	
	//max of requests that can execute at the same time 
	int maxOfRequest;	
	//thread pool
	private ExecutorService requestPool;
	
	//private ctor
	private RequestsManager() 
	{
		maxOfRequest=10;
		requestPool= Executors.newFixedThreadPool(maxOfRequest);		
	}
	  
	/**
	 * @return an instance of RequestsManager class (singleton)
	 */
	public static RequestsManager getInstance()
	{
		return DbManagerSingelton;		
	}
	
	/**
	 * add the user request to the requests queue for executing in it turn
	 * @param req - a user request (/update)
	 * @return 0 if failed, else if succeed
	 */	
	public int addRequest(Request req)
	{
		System.out.println("req manager");
		Future<Integer> future = requestPool.submit(req);
		
		try {
			return future.get();
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			System.out.println("future");
			e.printStackTrace();
		} catch (ExecutionException e) {
			// TODO Auto-generated catch block
			System.out.println("future");
			e.printStackTrace();
		}
		return 0;
		
	}
	
	
	public void stop()
	{
		requestPool.shutdown();
	}

}
